<?php

namespace wchat\wx\V3;

use Exception;
use wchat\wx\SmallProgram;

class WxV3Payment extends SmallProgram
{


    use WxV3PaymentTait;


    /**
     * @param string $orderNo
     * @param int $total
     * @param string|null $openId
     * @param string $payer_client_ip
     * @return array
     * @throws
     */
    public function payment(string $orderNo, int $total, ?string $openId = NULL, string $payer_client_ip = '127.0.0.1'): array
    {
        $body               = $this->getInitCore($orderNo, $total);
        $body['payer']      = ['openid' => $openId];
        $body['scene_info'] = ['payer_client_ip' => $payer_client_ip];

        $sign = $this->signature('POST', '/v3/pay/transactions/jsapi', $json = json_encode($body, JSON_UNESCAPED_UNICODE));

        $client = $this->createClient($sign, $json);
        $client->post('/v3/pay/transactions/jsapi');
        $client->close();

        $json = json_decode($client->getBody(), TRUE);
        if (!isset($json['prepay_id'])) {
            throw new Exception('微信支付调用失败: ' . $client->getBody());
        }

        return $this->createResponse($json, $body);
    }


}
